﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading.Tasks;

namespace FrameWork
{
   public class SocketRegister
   {
       public static Dictionary<string, IWebSocket> SocketList = new Dictionary<string, IWebSocket>();
#pragma warning restore CS1591 // 缺少对公共可见类型或成员“SocketRegister.SocketList”的 XML 注释

       public static void Register(IApplicationBuilder app)
       {
            app.UseWebSockets();
            app.Use(Acceptor);
        }
        private static async Task Acceptor(HttpContext httpContext, Func<Task> task)
        {
            if (!httpContext.WebSockets.IsWebSocketRequest) return;

            var socket = await httpContext.WebSockets.AcceptWebSocketAsync();

            var socketid = PublicTool.NewGuid(true);
            var isocket = new IWebSocket(socketid, socket);

            SocketList.Add(socketid, isocket);
            while (socket.State == WebSocketState.Open)
            {

            }
            SocketList.Remove(socketid);
        }
    }
}
